package com.polaris.live.ui.main.fragment

import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.LazyUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.FragmentLiveBroadcastBinding
import com.polaris.live.manager.UserStateManager
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.translation.R.string
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.utils.livehelper.LiveBroadHelper
import com.polaris.live.viewmodel.listeners.getUserLiveStream
import com.polaris.live.viewmodel.live.LiveBroadViewModel

/**
 * 直播
 *
 * @author Created by 半仙 on 2023/8/14/014 15:33
 */
class LiveBroadcastFragment : BaseVbFragment<LiveBroadViewModel, FragmentLiveBroadcastBinding>(),
    OnAutoRefreshListener {

    private var mLiveNextAttempt: Int = 0
    private lateinit var mLiveBroadHelper: LiveBroadHelper
    override fun initView(savedInstanceState: Bundle?) {
        updateImmersionBar()
        mBinding.smartFresh.setEnableLoadMore(false)
        mLiveBroadHelper = LiveBroadHelper(mBinding.vpPager, object : LiveBroadHelper.HelperCallBack {
            override fun getFirstData() {
            }

            override fun getNextDataById(userid: Long?) {
                mViewModel.getLoadMore(userid)
            }

            override fun getUserLiveState(userid: Long) {
                mViewModel.getUserLiveStream(userid)
            }

            override fun OnItemClickListener(view: View, displayUserBean: DisplayUserBean) {
                if (displayUserBean.base.living == AppConst.YES) {
                    context?.also {
                        GlobalPopupManager.showCompletePopup(it) {
                            ViewUtils.getAliveTopCompatActivity()?.also { a ->
                                LiveUtils.toSpectator(displayUserBean).navigation(a)
                            }
                        }
                    }
                } else {
                    ToastGravity.showGravity(StringUtils.getString(string.down_streamed))
                }
            }

        }, this)
        initObserver()
        initListener()
    }

    private fun initListener() {
        mBinding.startLive.setOnSingleClickListener {
            StartLiveProxy.builder(this)
                .startLive(mViewModel, LiveConst.Type.ONLY_LIVE)
        }

        mBinding.smartFresh.setOnRefreshListener {
            refresh()
        }
    }

    private fun initObserver() {
        //滑动更多
        mViewModel.liveLoadMoreLiveData.observe(this) { resultState ->
            mBinding.smartFresh.finishRefresh()
            parseState(resultState, {
                mLiveNextAttempt = 0
                mLiveBroadHelper.addData(it)
            }, {
                reFetchLoadMore(1000)
            })
        }

        mViewModel.userLiveLiveData.observe(this) {
            mLiveBroadHelper.updateData(it)
        }

        //监听将关闭的删除
        UserStateManager.observe(this, {
            mLiveBroadHelper.getUserStateIds()
        }, { messages ->
            mLiveBroadHelper.setUserStateChange(messages)
        })
    }

    /**
     * 出错了指数延迟获取新的
     */
    private fun reFetchLoadMore(initDelay: Long) {
        val delay = LazyUtils.exponentialBackoff(mLiveNextAttempt++, initDelay)
        mViewModel.getLoadMore(mLiveBroadHelper.getCurrentUserId(), delay)
    }

    override fun initData() {

    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!isCreated()) {
            return
        }
        if (!hidden) {
            onAutoRefresh()
        } else {
            mLiveBroadHelper.stopLive()
        }
    }

    private fun updateImmersionBar() {
        NavigationBarUtils.setImmersionBarForMainLive(this, mBinding.clTitle)
    }

    override fun onResume() {
        super.onResume()
        if (isVisible && isResumed) {
            mLiveBroadHelper.onResumeLive()
        }
    }

    override fun onStop() {
        super.onStop()
        mLiveBroadHelper.stopLive()
    }

    override fun onDestroy() {
        super.onDestroy()
        mLiveBroadHelper.releaseLive()
    }

    private fun refresh() {
        mLiveBroadHelper.clearData()
    }

    override fun onAutoRefresh() {
        if (!isCreated()) {
            return
        }
        mBinding.smartFresh.autoRefresh()
    }
}